package com.gues.shiro;

import com.gues.eneity.*;
import com.gues.service.*;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

public class MyRealm extends AuthorizingRealm {

    @Autowired
    UserService userService;

    @Autowired
    UserRoleService userRoleService;

    @Autowired
    RoleService roleService;

    @Autowired
    RolePermissionService rolePermissionService;

    @Autowired
    PermissionService permissionService;

    // 授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        String username = (String) principalCollection.getPrimaryPrincipal();
        // 添加角色
        User user = userService.selectByUsername(username);
        List<UserRole> userRoles = userRoleService.selectByUserId(user.getUserId());
        for ( UserRole userRole : userRoles) {
            Role role = roleService.selectByRoleId(userRole.getRoleId());
            simpleAuthorizationInfo.addRole(role.getRoleName());

            // 添加权限
            List<RolePermission> rolePermissions = rolePermissionService.selectByRoleId(role.getRoleId());
            for( RolePermission rolePermission : rolePermissions) {
                Permission permission = permissionService.selectByPermissionId(rolePermission.getPermissionId());
                simpleAuthorizationInfo.addStringPermission(permission.getPermission());
            }
        }

        return simpleAuthorizationInfo;
    }
    // 认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String username = (String) authenticationToken.getPrincipal();

        User user = userService.selectByUsername(username);

        if ( null != user) {
            return new SimpleAuthenticationInfo(username, user.getPassword(), this.getName());
            // 加盐加密的
            // return new SimpleAuthenticationInfo(username, user.getPassword(), ByteSource.Util.bytes(user.getSalt()), this.getName());
        }
        return null;
    }
}
